


package jnpf.zcasset.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.xuyanwu.spring.file.storage.FileInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.base.vo.DownloadVO;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.config.ConfigValueUtil;
import jnpf.exception.DataException;
import jnpf.permission.entity.UserEntity;
import jnpf.util.*;
import jnpf.zcasset.entity.ZcAssetFinanceEntity;
import jnpf.zcasset.model.zcassetfinance.ZcAssetFinanceForm;
import jnpf.zcasset.model.zcassetfinance.ZcAssetFinanceInfoVO;
import jnpf.zcasset.model.zcassetfinance.ZcAssetFinanceListVO;
import jnpf.zcasset.model.zcassetfinance.ZcAssetFinancePagination;
import jnpf.zcasset.service.ZcAssetFinanceService;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 *
 * 资产融资
 * @版本： V3.2.0
 * @版权： 智果云科技（https://www.jnpfsoft.com）
 * @作者： JNPF开发平台组
 * @日期：
 */
@Slf4j
@RestController
@Api(tags = "资产融资" , value = "zc")
@RequestMapping("/api/zc/ZcAssetFinance")
public class ZcAssetFinanceController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private ConfigValueUtil configValueUtil;

    @Autowired
    private UserProvider userProvider;


    @Autowired
    private ZcAssetFinanceService zcAssetFinanceService;



    /**
     * 列表
     *
     * @param zcAssetFinancePagination
     * @return
     */
    @ApiOperation("获取列表")
	@PostMapping("/getList")
    public ActionResult list(@RequestBody ZcAssetFinancePagination zcAssetFinancePagination)throws IOException{
        List<ZcAssetFinanceEntity> list= zcAssetFinanceService.getList(zcAssetFinancePagination);
        //处理id字段转名称，若无需转或者为空可删除

    List<ZcAssetFinanceListVO> listVO=JsonUtil.getJsonToList(list,ZcAssetFinanceListVO.class);
    for(ZcAssetFinanceListVO zcAssetFinanceVO:listVO){
                zcAssetFinanceVO.setAssetId_name(generaterSwapUtil.getDynName("612769091110831365" ,"ASSET_NAME" ,"id","" ,zcAssetFinanceVO.getAssetId(),false));

                zcAssetFinanceVO.setFinanceStartDate_name(zcAssetFinanceVO.getFinanceStartDate());

                zcAssetFinanceVO.setFinanceEndDate_name(zcAssetFinanceVO.getFinanceEndDate());

                zcAssetFinanceVO.setFinanceAmount_name(zcAssetFinanceVO.getFinanceAmount());

                zcAssetFinanceVO.setFinanceContract_name(zcAssetFinanceVO.getFinanceContract());

                zcAssetFinanceVO.setFinancePurpose_name(zcAssetFinanceVO.getFinancePurpose());

                zcAssetFinanceVO.setCreditor_name(zcAssetFinanceVO.getCreditor());

                zcAssetFinanceVO.setDebtor_name(zcAssetFinanceVO.getDebtor());

                zcAssetFinanceVO.setRemark_name(zcAssetFinanceVO.getRemark());

                zcAssetFinanceVO.setAttachmentUrls_name(generaterSwapUtil.getFileNameInJson(zcAssetFinanceVO.getAttachmentUrls()));

		//子表数据转换
     }

         PageListVO vo=new PageListVO();
         vo.setList(listVO);
         PaginationVO page=JsonUtil.getJsonToBean(zcAssetFinancePagination,PaginationVO.class);
         vo.setPagination(page);
         return ActionResult.success(vo);

    }

    /**
     * 创建
     *
     * @param zcAssetFinanceForm
     * @return
     */
    @PostMapping
    @Transactional
    @ApiOperation("创建")
    public ActionResult create(@RequestBody @Valid ZcAssetFinanceForm zcAssetFinanceForm) throws DataException {
        boolean b =  zcAssetFinanceService.checkForm(zcAssetFinanceForm,0);
        if (b){
         return ActionResult.fail("单行输入不能重复");
        }
        String mainId =RandomUtil.uuId();

        UserInfo userInfo=userProvider.get();
		UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        ZcAssetFinanceEntity entity = JsonUtil.getJsonToBean(zcAssetFinanceForm, ZcAssetFinanceEntity.class);
            entity.setId(mainId);
                zcAssetFinanceService.save(entity);


        return ActionResult.success("创建成功");
}



    /**
    * 模板下载
    *
    * @return
    */
    @ApiOperation("模板下载")
    @GetMapping("/TemplateDownload")
    public ActionResult<DownloadVO>  TemplateDownload(){
        UserInfo userInfo=userProvider.get();
        DownloadVO vo=DownloadVO.builder().build();
        try{
            vo.setName("职员信息.xlsx");
            vo.setUrl(UploaderUtil.uploaderFile("/api/Common/DownloadModel?encryption=" ,userInfo.getId()+"#"+"职员信息.xlsx"+"#"+"Temporary"));
        }catch(Exception e){
            log.error("信息导出Excel错误:{}" ,e.getMessage());
        }
        return ActionResult.success(vo);
    }

    /**
    * 导出Excel
    *
    * @return
    */
    @ApiOperation("导出Excel")
    @PostMapping("/Actions/Export")
    public ActionResult Export(@RequestBody ZcAssetFinancePagination zcAssetFinancePagination) throws IOException {
        if (StringUtil.isEmpty(zcAssetFinancePagination.getSelectKey())){
            return ActionResult.fail("请选择导出字段");
        }
        List<ZcAssetFinanceEntity> list = zcAssetFinanceService.getTypeList(zcAssetFinancePagination,zcAssetFinancePagination.getDataType());
        //处理id字段转名称，若无需转或者为空可删除

    List<ZcAssetFinanceListVO> listVO=JsonUtil.getJsonToList(list,ZcAssetFinanceListVO.class);
    for(ZcAssetFinanceListVO zcAssetFinanceVO:listVO){
                zcAssetFinanceVO.setAssetId_name(generaterSwapUtil.getDynName("612769091110831365" ,"ASSET_NAME" ,"id","" ,zcAssetFinanceVO.getAssetId(),false));

                zcAssetFinanceVO.setFinanceStartDate_name(zcAssetFinanceVO.getFinanceStartDate());

                zcAssetFinanceVO.setFinanceEndDate_name(zcAssetFinanceVO.getFinanceEndDate());

                zcAssetFinanceVO.setFinanceAmount_name(zcAssetFinanceVO.getFinanceAmount());

                zcAssetFinanceVO.setFinanceContract_name(zcAssetFinanceVO.getFinanceContract());

                zcAssetFinanceVO.setFinancePurpose_name(zcAssetFinanceVO.getFinancePurpose());

                zcAssetFinanceVO.setCreditor_name(zcAssetFinanceVO.getCreditor());

                zcAssetFinanceVO.setDebtor_name(zcAssetFinanceVO.getDebtor());

                zcAssetFinanceVO.setRemark_name(zcAssetFinanceVO.getRemark());

                zcAssetFinanceVO.setAttachmentUrls_name(generaterSwapUtil.getFileNameInJson(zcAssetFinanceVO.getAttachmentUrls()));

		//子表数据转换
     }

        //转换为map输出
        List<Map<String, Object>>mapList=JsonUtil.getJsonToListMap(JsonUtil.getObjectToStringDateFormat(listVO,"yyyy-MM-dd HH:mm:ss"));
            mapList.stream().forEach(map -> {
            Map<String,Object> map2 =new HashMap<>();
            map.putAll(map2);
            });
        String[]keys=!StringUtil.isEmpty(zcAssetFinancePagination.getSelectKey())?zcAssetFinancePagination.getSelectKey().split(","):new String[0];
        UserInfo userInfo=userProvider.get();
        DownloadVO vo=this.creatModelExcel(configValueUtil.getTemporaryFilePath(),mapList,keys,userInfo);
        return ActionResult.success(vo);
    }
    //导出表格
    public DownloadVO creatModelExcel(String path,List<Map<String, Object>>list,String[]keys,UserInfo userInfo){
        DownloadVO vo=DownloadVO.builder().build();
            List<ExcelExportEntity> entitys=new ArrayList<>();
            if(keys.length>0){
                for(String key:keys){
                    switch(key){
                    case "assetId" :
                    entitys.add(new ExcelExportEntity("资产信息" ,"assetId_name"));
                    break;
                    case "financeStartDate" :
                    entitys.add(new ExcelExportEntity("融资日期" ,"financeStartDate_name"));
                    break;
                    case "financeEndDate" :
                    entitys.add(new ExcelExportEntity("融资结束日期" ,"financeEndDate_name"));
                    break;
                    case "financeAmount" :
                    entitys.add(new ExcelExportEntity("融资金额" ,"financeAmount_name"));
                    break;
                    case "financeContract" :
                    entitys.add(new ExcelExportEntity("融资合同" ,"financeContract_name"));
                    break;
                    case "financePurpose" :
                    entitys.add(new ExcelExportEntity("融资用途" ,"financePurpose_name"));
                    break;
                    case "creditor" :
                    entitys.add(new ExcelExportEntity("债权人" ,"creditor_name"));
                    break;
                    case "debtor" :
                    entitys.add(new ExcelExportEntity("债务人" ,"debtor_name"));
                    break;
                    case "remark" :
                    entitys.add(new ExcelExportEntity("备注" ,"remark_name"));
                    break;
                    case "attachmentUrls" :
                    entitys.add(new ExcelExportEntity("附件" ,"attachmentUrls_name"));
                    break;
            default:
                    break;

                    }
                }
				List<String> keylist = new ArrayList<>();
				for (String key:keys){
				    keylist.add(key);
				}
            }

        ExportParams exportParams = new ExportParams(null, "表单信息");
        exportParams.setType(ExcelType.XSSF);
        try{
		@Cleanup Workbook workbook = new HSSFWorkbook();
        if (entitys.size()>0){
            if (list.size()==0){
				list.add(new HashMap<>());
            }
            workbook = ExcelExportUtil.exportExcel(exportParams, entitys, list);
        }
        String fileName = "表单信息" + DateUtil.dateNow("yyyyMMdd") + "_" + RandomUtil.uuId() + ".xlsx";

        String temporaryFilePath = configValueUtil.getTemporaryFilePath();
        MultipartFile multipartFile = ExcelUtil.workbookToCommonsMultipartFile(workbook, fileName);
        FileInfo fileInfo = FileUploadUtils.uploadFile(multipartFile, temporaryFilePath, fileName);
        vo.setName(fileInfo.getFilename());
        vo.setUrl(UploaderUtil.uploaderFile(fileInfo.getFilename() + "#" + "Temporary") + "&name=" + fileName);
        } catch (Exception e) {
            log.error("信息导出Excel错误:{}", e.getMessage());
            e.printStackTrace();
        }
        return vo;
    }



    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/batchRemove/{ids}")
    @Transactional
    @ApiOperation("批量删除")
    public ActionResult batchRemove(@PathVariable("ids") String ids){
        String[] idList = ids.split(",");
		int i =0;
        for (String allId : idList){
            this.delete(allId);
            i++;
        }
        if (i == 0 ){
            return ActionResult.fail("删除失败");
        }
            return ActionResult.success("删除成功");
    }


    /**
    * 信息
    *
    * @param id
    * @return
    */
    @ApiOperation("信息")
    @GetMapping("/{id}")
    public ActionResult<ZcAssetFinanceInfoVO> info(@PathVariable("id") String id){
        ZcAssetFinanceEntity entity= zcAssetFinanceService.getInfo(id);
        ZcAssetFinanceInfoVO vo=JsonUtil.getJsonToBean(entity, ZcAssetFinanceInfoVO.class);

    //子表
    //副表
        return ActionResult.success(vo);
    }

    /**
    * 表单信息(详情页)
    *
    * @param id
    * @return
    */
    @ApiOperation("表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult<ZcAssetFinanceInfoVO> detailInfo(@PathVariable("id") String id){
        ZcAssetFinanceEntity entity= zcAssetFinanceService.getInfo(id);
        ZcAssetFinanceInfoVO vo=JsonUtil.getJsonToBean(entity, ZcAssetFinanceInfoVO.class);

 //子表数据转换

 //附表数据转换

//添加到详情表单对象中
                vo.setAssetId(generaterSwapUtil.getDynName("612769091110831365" ,"ASSET_NAME" ,"id","" ,vo.getAssetId(),false));

                vo.setFinanceStartDate(vo.getFinanceStartDate());

                vo.setFinanceEndDate(vo.getFinanceEndDate());

                vo.setFinanceAmount(vo.getFinanceAmount());

                vo.setFinanceContract(vo.getFinanceContract());

                vo.setFinancePurpose(vo.getFinancePurpose());

                vo.setCreditor(vo.getCreditor());

                vo.setDebtor(vo.getDebtor());

                vo.setRemark(vo.getRemark());

                vo.setAttachmentUrls(generaterSwapUtil.getFileNameInJson(vo.getAttachmentUrls()));


        return ActionResult.success(vo);
		}




   /**
    * 更新
    *
    * @param id
    * @param zcAssetFinanceForm
    * @return
    */
    @PutMapping("/{id}")
    @Transactional
    @ApiOperation("更新")
    public ActionResult update(@PathVariable("id") String id,@RequestBody @Valid ZcAssetFinanceForm zcAssetFinanceForm) throws DataException {
        boolean b =  zcAssetFinanceService.checkForm(zcAssetFinanceForm,1);
        if (b){
         return ActionResult.fail("单行输入不能重复");
        }
        UserInfo userInfo=userProvider.get();
        ZcAssetFinanceEntity entity= zcAssetFinanceService.getInfo(id);
        if(entity!=null){
            ZcAssetFinanceEntity subentity=JsonUtil.getJsonToBean(zcAssetFinanceForm, ZcAssetFinanceEntity.class);
				boolean b1 = zcAssetFinanceService.updateById(subentity);
				if (!b1){
				return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
				}
        return ActionResult.success("更新成功");
        }else{
            return ActionResult.fail("更新失败，数据不存在");
        }
    }



   /**
    * 删除
    *
    * @param id
    * @return
    */
    @ApiOperation("删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id){
        ZcAssetFinanceEntity entity= zcAssetFinanceService.getInfo(id);
        if(entity!=null){
            zcAssetFinanceService.delete(entity);

        }
        return ActionResult.success("删除成功");
    }











}
